"""
1、往yaml文件中写入返回结果并读取
2、断言中加入函数
3、添加内容时加入函数 例如随机数、随机姓名等
"""
import string
import time

from faker import Faker
from faker.generator import random

from utils.YamlUtil import YamlUtil
from utils.log_util import logger
from utils.read import FileRead
from utils.yaml_util import fake
from datetime import datetime, timedelta
from utils.mysql_util import db


class CustomMethod:
    """
    所有的自动生成的方法写到该文件下，比如生成随机数，数据库查询等
    """

    def __init__(self):
        self.read = FileRead()
        self.yaml_util = YamlUtil()

    def get_extract_value(self, key):
        """
        从extract.yaml中获取内容
        :param key:
        :return:
        """
        try:
            data = self.yaml_util.read_extra_yaml()  # 拂去extra_yaml内容
            return data[key]  # 返回data中的[key]值
        except Exception as e:
            logger.error(f'从yaml文件中根据{key}获取不到内容，error={e}')

    def get_extract_host(self, key):
        """从setting.ini种获取域名地址提取后格式化"""
        try:
            data = self.read.read_ini()['host']
            return data[key]
        except Exception as e:
            logger.error(f'从setting.ini文件种根据{key}获取不到内容，error={e}')

    def get_time(self):
        """
        时间戳转换
        :return:
        """
        timestamp = int(time.time() * 1000)
        return timestamp

    def get_formate_time_y(self):
        """
                        格式化时间年月日
                        :return:
                        """
        timestamp = int(time.time())
        formatted_date = time.strftime("%Y-%m-%d", time.localtime(timestamp))
        return formatted_date

    def get_formate_time(self):  # 精确到时分秒
        """
                格式化时间年月日时分秒
                :return:
                """
        timestamp = int(time.time())
        formatted_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
        return formatted_date

    def get_today_start_time(self):
        """
        获取当天时间0点
        """
        now = datetime.now()  # 获取当前时间
        start_time = datetime(now.year, now.month, now.day)  # 构造当天零点时间

        return start_time

    def get_random(self, num1, num2):
        return random.randint(num1, num2)

    def get_random_number(self):
        # 生成一个15位的随机数
        return str(random.randint(10 ** 14, 10 ** 15 - 1))

    def get_random_name(self):
        """
        生成随机中文名字
        """
        return fake.name()  # 固定函数用法，生成中文名字

    def get_random_phone(self):
        """
        生成随机手机号
        """
        three_digits = random.choice(
            ['135', '136', '137', '138', '139', '150', '151', '152', '158', '159', '182', '183', '187', '188'])

        # 生成手机号的后八位（即剩余部分）
        eight_digits = ''.join(random.choice(string.digits) for _ in range(8))

        # 将开头和剩余部分拼接起来形成完整的手机号
        phone_number = three_digits + eight_digits

        return phone_number

    # def get_random_id_number(self):
    #     """
    #     随机生成身份证件号码
    #     """
    #     fake = Faker('zh_CN')
    #     id_number = fake.ssn()
    #     return id_number
    def get_random_id_number(self):
        # 随机生成地区码（示例使用"110105"代表北京市朝阳区）
        area_code = "110105"

        # 随机生成出生年份（16-50岁之间）
        birth_year = random.randint(1975, 2007)

        # 随机生成出生月份（01-12之间）
        birth_month = str(random.randint(1, 12)).zfill(2)

        # 随机生成出生日期（01-28之间）
        birth_day = str(random.randint(1, 28)).zfill(2)

        # 随机生成顺序码（3位数字）
        sequence_code = str(random.randint(0, 999)).zfill(3)

        # 计算校验码
        id_base = area_code + str(birth_year) + birth_month + birth_day + sequence_code
        check_code = self.generate_check_code(id_base)

        # 组合生成最终的身份证号码
        id_number = id_base + check_code

        return id_number

    def generate_check_code(self, base):
        factors = [int(x) for x in list(base)]
        weights = [int(x) for x in '7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2'.split()]
        check_codes = '10X98765432'

        check_sum = sum([f * w for f, w in zip(factors, weights)]) % 11
        check_code = check_codes[check_sum]

        return check_code

    def calculate_age(self):
        """
        根据身份证获取当前年龄
        """
        id_number = self.get_random_id_number()
        birth_year = int(id_number[6:10])  # 获取身份证号码中的出生年份
        current_year = datetime.now().year
        age = current_year - birth_year
        return age

    def get_gender(self):
        """
        获取身份证性别 id_number是身份证号码
        """
        id_number = self.get_random_id_number()
        gender_digit = int(id_number[-2])  # 获取身份证号码倒数第二位数字

        if gender_digit % 2 == 0:
            return "女"
        else:
            return "男"

    def get_birthdate(self):
        """
        根据身份证号码获取出生年月日
        """
        id_number = self.get_random_id_number()
        birthdate = id_number[6:14]  # 获取身份证号码中的出生年月日
        try:
            birthdate = datetime.strptime(birthdate, "%Y%m%d").date()
            return birthdate.strftime("%Y-%m-%d")
        except ValueError:
            return None

    def generate_birthdate(self, times):
        """
        劳务管理专用-根据参数生成年龄小于16或者大于50的年月日
        """
        current_year = datetime.now().year

        if times == "min":
            start_year = current_year - 16  # 生成在过去16年内的年份
            end_year = current_year - 1  # 生成在过去1年内的年份
        elif times == "max":
            start_year = current_year - 80  # 生成在过去80年内的年份
            end_year = current_year - 50  # 生成在过去50年内的年份
        else:
            return None

        random_year = random.randint(start_year, end_year)
        random_month = random.randint(1, 12)

        if random_year == start_year and random_month > datetime.now().month:
            random_month = datetime.now().month

        last_day_of_month = (datetime(random_year, random_month, 1) + timedelta(days=32)).replace(day=1) - timedelta(
            days=1)
        random_day = random.randint(1, last_day_of_month.day)

        return datetime(random_year, random_month, random_day).strftime("%Y-%m-%d")

    # 劳务专用函数
    def calculate_age_birthdate(self, age):
        """
        劳务管理专用-根据出生年月获取年龄
        """
        if age == "min":
            birthdate = self.generate_birthdate("min")
        elif age == "max":
            birthdate = self.generate_birthdate("max")
        else:
            return None
        birthdate1 = datetime.strptime(birthdate, "%Y-%m-%d")
        current_date = datetime.now()

        age = current_date.year - birthdate1.year

        if current_date.month < birthdate1.month or (
                current_date.month == birthdate1.month and current_date.day < birthdate1.day
        ):
            age -= 1

        return age

    def expect_value_spray(self):
        """
        自动喷淋查询列表数据量-断言中加入函数，该函数可写入sql查询结果并进行断言
        与数据库结合
        """
        sql = "SELECT Count(Id) FROM `tsprayequip` WHERE IsDelete=0"
        result = db.select_db_one(sql)
        return result['Count(Id)']

    def expect_value_labor_num(self):
        """劳务查询人员数量"""
        sql = "SELECT Count(Id) FROM `tlaborpersonal` WHERE IsDelete=0 AND FlatType=0 AND ProjectID=39"
        result = db.select_db_one(sql)
        return result['Count(Id)']

    def expect_value_check_recoder_num(self):
        """查询检查记录仪设备数量"""
        sql = "SELECT Count(Id) FROM `t_inspect_device` WHERE IsDelete=0 AND ProjectID=39"
        result = db.select_db_one(sql)
        return result['Count(Id)']

    """ 军队计算"""

    def calculation_result1(self):
        # 建筑工程原始数据投资额
        engineering_scale = CustomMethod().get_extract_value('engineering_scale')
        engineering_baseprice = CustomMethod().get_extract_value('engineering_baseprice')
        investment_amount = engineering_scale * engineering_baseprice
        return int(investment_amount)

    def calculation_result2(self):
        # 建筑工程坡面屋投资额
        slope_scale = CustomMethod().get_extract_value('slope_scale')
        slope_baseprice = CustomMethod().get_extract_value('slope_baseprice')
        slope_amount = slope_scale * slope_baseprice
        return int(slope_amount)





# if __name__ == '__main__':
#     CustomMethod().calculation_result5()
